# 酒吧管理系统部署脚本 (Windows)
# 使用方法: .\deploy.ps1

$SERVER_IP = "156.226.176.183"
$SERVER_USER = "root"
$REMOTE_DIR = "/opt/bar-system"

Write-Host "开始部署到服务器 $SERVER_IP..." -ForegroundColor Green

# 1. 打包项目（排除 node_modules）
Write-Host "`n[1/5] 打包项目文件..." -ForegroundColor Yellow
$timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
$packageName = "bar-system-$timestamp.tar.gz"

# 使用 tar 打包（Windows 10+ 自带）
tar -czf $packageName `
    --exclude='node_modules' `
    --exclude='.git' `
    --exclude='*.log' `
    --exclude='.env' `
    backend/ web/ user-web/ package.json

if ($LASTEXITCODE -ne 0) {
    Write-Host "打包失败！" -ForegroundColor Red
    exit 1
}

Write-Host "打包完成: $packageName" -ForegroundColor Green

# 2. 上传到服务器
Write-Host "`n[2/5] 上传文件到服务器..." -ForegroundColor Yellow
scp $packageName "${SERVER_USER}@${SERVER_IP}:/tmp/"

if ($LASTEXITCODE -ne 0) {
    Write-Host "上传失败！请检查SSH连接。" -ForegroundColor Red
    exit 1
}

# 3. 执行服务器端部署
Write-Host "`n[3/5] 在服务器上执行部署..." -ForegroundColor Yellow
$deployScript = @"
#!/bin/bash
set -e

echo '=== 开始部署酒吧管理系统 ==='

# 安装必要软件
echo '[1/6] 检查并安装必要软件...'
apt-get update
apt-get install -y nodejs npm mysql-server nginx

# 配置 MySQL
echo '[2/6] 配置数据库...'
systemctl start mysql
systemctl enable mysql

# 创建数据库和用户（如果不存在）
mysql -e "CREATE DATABASE IF NOT EXISTS bar_system CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" 2>/dev/null || true
mysql -e "CREATE USER IF NOT EXISTS 'bar_user'@'localhost' IDENTIFIED BY 'Bar@123456';" 2>/dev/null || true
mysql -e "GRANT ALL PRIVILEGES ON bar_system.* TO 'bar_user'@'localhost';" 2>/dev/null || true
mysql -e "FLUSH PRIVILEGES;" 2>/dev/null || true

# 创建部署目录
echo '[3/6] 解压项目文件...'
mkdir -p $REMOTE_DIR
cd /tmp
tar -xzf bar-system-*.tar.gz -C $REMOTE_DIR --strip-components=0

# 安装后端依赖
echo '[4/6] 安装后端依赖...'
cd $REMOTE_DIR/backend
npm install --production

# 创建后端环境变量文件
cat > .env << 'EOF'
NODE_ENV=production
PORT=3000
JWT_SECRET=your-secret-key-change-this-in-production
JWT_EXPIRE=7d

DB_HOST=localhost
DB_PORT=3306
DB_NAME=bar_system
DB_USER=bar_user
DB_PASSWORD=Bar@123456
EOF

# 初始化数据库
echo '[5/6] 初始化数据库...'
node src/scripts/initDb.js

# 配置 PM2（进程管理）
npm install -g pm2
pm2 delete bar-backend 2>/dev/null || true
pm2 start src/server.js --name bar-backend
pm2 save
pm2 startup

# 安装前端依赖并构建
echo '[6/6] 构建前端...'
cd $REMOTE_DIR/web
npm install
npm run build

cd $REMOTE_DIR/user-web
npm install
npm run build

# 配置 Nginx
cat > /etc/nginx/sites-available/bar-system << 'NGINX_EOF'
# 后台管理系统
server {
    listen 35280;
    server_name _;
    
    root $REMOTE_DIR/web/dist;
    index index.html;
    
    location / {
        try_files \$uri \$uri/ /index.html;
    }
    
    location /api/ {
        proxy_pass http://localhost:3000/api/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host \$host;
        proxy_cache_bypass \$http_upgrade;
    }
}

# 用户端
server {
    listen 19006;
    server_name _;
    
    root $REMOTE_DIR/user-web/dist;
    index index.html;
    
    location / {
        try_files \$uri \$uri/ /index.html;
    }
    
    location /api/ {
        proxy_pass http://localhost:3000/api/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host \$host;
        proxy_cache_bypass \$http_upgrade;
    }
}
NGINX_EOF

ln -sf /etc/nginx/sites-available/bar-system /etc/nginx/sites-enabled/
nginx -t && systemctl restart nginx

# 配置防火墙
ufw allow 35280/tcp
ufw allow 19006/tcp
ufw allow 3000/tcp

echo ''
echo '=== 部署完成！==='
echo '后台管理系统: http://$SERVER_IP:35280'
echo '用户端: http://$SERVER_IP:19006'
echo '后端API: http://$SERVER_IP:3000'
echo ''
echo '默认管理员账号:'
echo '手机号: 13800138000'
echo '密码: admin123'
"@

# 将部署脚本保存到临时文件
$deployScript | Out-File -FilePath "deploy-server.sh" -Encoding UTF8

# 上传并执行部署脚本
scp deploy-server.sh "${SERVER_USER}@${SERVER_IP}:/tmp/"
ssh "${SERVER_USER}@${SERVER_IP}" "chmod +x /tmp/deploy-server.sh && /tmp/deploy-server.sh"

# 清理临时文件
Write-Host "`n[4/5] 清理临时文件..." -ForegroundColor Yellow
Remove-Item $packageName -Force
Remove-Item deploy-server.sh -Force

Write-Host "`n[5/5] 部署完成！" -ForegroundColor Green
Write-Host "`n访问地址:" -ForegroundColor Cyan
Write-Host "  后台管理: http://$SERVER_IP:35280" -ForegroundColor White
Write-Host "  用户端:   http://$SERVER_IP:19006" -ForegroundColor White
Write-Host "`n默认管理员账号:" -ForegroundColor Cyan
Write-Host "  手机号: 13800138000" -ForegroundColor White
Write-Host "  密码:   admin123" -ForegroundColor White
